{% extends "sitebase.html" %}
{% block title %}Versus - Compare Buildings Side by Side{% endblock %}

{% block extra_scriptsCSS_imports %}
<link href="/site-media/anytime/anytimec.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="/site-media/flot/jquery.flot.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.stack.min.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.navigate.min.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.selection.min.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.axislabels.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.resize.min.js"></script>
<script type="text/javascript" src="/site-media/anytime/anytimec.js"></script>
<script type="text/javascript" src="/site-media/bootstrap/bootstrap-modal.js"></script>
<link rel="stylesheet" href="/site-media/jgauge/css/jgauge.css" type="text/css" /> <!-- CSS for jGauge styling. -->
<!--[if IE]><script type="text/javascript" language="javascript" src="js/excanvas.min.js"></script><![endif]--> <!-- Extends canvas support to IE. (Possibly buggy, need to look into this.) -->
<script type="text/javascript" src="/site-media/jgauge/js/jQueryRotate.min.js"></script> <!-- jQueryRotate plugin used for needle movement. -->
<script type="text/javascript" src="/site-media/jgauge/js/jgauge-0.3.0.a3.js"></script> <!-- jGauge JavaScript. -->
<script type="text/javascript" src="/site-media/psMathStats/psMathStats.min.js"></script>
<script type="text/javascript" src="/site-media/jquery-sparkline/jquery.sparkline.js"></script>


<!-- customs -->
<script type="text/javascript" src="/site-media/campenportJS/buildingpage/gaugeSetup.js"></script>
<script type="text/javascript" src="/site-media/campenportJS/smap/query.js"></script>
<script type="text/javascript" src="/site-media/campenportJS/buildingpage/statsCalc.js"></script>
{% endblock %}
{% block menu_6 %}class="active" {% endblock %}
{% block extra_css_inline %}
	.hero-unit {
		padding-top: 20px;
		padding-bottom: 20px;
		padding-right: 20px;
		padding-left: 20px;
	}
	footer {
		 margin-top: 0px; 
	}
{% endblock %}

{% block header_title %}
<a href="/buildings/{{ SHORT_NAME }}" style="color:#000000;">Versus</a>
{% endblock %}
{% block header_subtitle %}
Compare two buildings side-by-side.
{% endblock %}

{% block content_inside %}
<div class="hero-unit" style="min-height:610px;margin-top:0px;" id="graphMain">
<h2>Live Power Consumption Graph (Default 1 Day): </h2> Start Time: <input class="span4" type = "text" id="date2" size=36>&nbsp; &nbsp;  End Time: <input class="span4" type="text" id="date" size=36> &nbsp; &nbsp; <input type = "button" class="btn primary" value = "Load/Refresh Data" id="refresh"> &nbsp; &nbsp;<input type="checkbox" id="autoup" name="autoup" value="10" checked /> Autoupdate (15 min)
<br><br>
<div id="selectors"><div id="sel1" style="float:left;"><form action="/search/" method="get" class="pull-right">
					<input id="searchbox2" class="input-medium" type="text" placeholder="First Building" name="name">          
				</form></div><div id="sel2" style="float:right;"><form action="/search/" method="get" class="pull-right">
					<input id="searchbox3" class="input-medium" type="text" placeholder="Second Building" name="name">          
				</form></div><br>
</div><br><br>
<div id="graph" >
<!-- contains graph generated by flot -->
<div id="placeholder" style = "float:left;position:absolute;width:440px;height:520px;">
</div><div id="loading" style="position:absolute;width:300px;top:450px;left:35%;margin-left:-150px;text-align:center;padding:7px 0 0 0;font:bold 11px Arial, Helvetica, sans-serif;">  
    Loading data, please wait..  
    <img src="/site-media/images/ajax-loader.gif" alt="loading.." />  
    </div> 
	<div id="enter" style="position:absolute;width:300px;top:450px;left:35%;margin-left:-150px;text-align:center;padding:7px 0 0 0;font:bold 11px Arial, Helvetica, sans-serif;">  
    Type in a building name. The graph will appear here.
    </div> 

</div>
<div id="placeholder2" style = "float:right;position:absolute;width:440px;height:520px;margin-left:460px;">
</div><div id="loading2" style="position:absolute;width:300px;top:450px;left:65%;margin-left:-150px;text-align:center;padding:7px 0 0 0;font:bold 11px Arial, Helvetica, sans-serif;">  
    Loading data, please wait..  
    <img src="/site-media/images/ajax-loader.gif" alt="loading.." />  
    </div> 
	<div id="enter2" style="position:absolute;width:300px;top:450px;left:65%;margin-left:-150px;text-align:center;padding:7px 0 0 0;font:bold 11px Arial, Helvetica, sans-serif;">  
    Type in a building name. The graph will appear here.
	</div>
</div>








{% endblock %}
{% block extend_contact_url %}{{ A_SHORT_NAME }}{% endblock %}
{% block random_extras %}
<script type="text/javascript">
/*
 * the following two functions are helpers for smooth anchor-scrolling
 */
function scrollDownTo(itemID){
     	$('html,body').animate({scrollTop: $("#"+itemID).offset().top-40},'slow');
}
function scrollToTop(){
     	$('html,body').animate({scrollTop: 0},'slow');
}



/*
 * Handler function for Bootstrap Popovers
 */
$(function () {
              $("a[rel=popover]")
                .popover({
                  offset: 10
                })
                .click(function(e) {
                  e.preventDefault()
                })
            })
$(function() {
		var availableTags = [
			{% for building in buildings|dictsort:"longname" %}
			"{{ building.longname }}",
			{% endfor %}
		];
		var getURLbuild = {
			{% for building in buildings|dictsort:"longname" %}
			"{{ building.longname }}": '/buildings/{{ building.shortname }}/',
			{% endfor %}
		};
		$( "#searchbox2" ).autocomplete({
			source: availableTags,
//	$("#placeholder").empty();

			select: function(event, ui) { window.mainFlotTimeseries = {}; $("#searchbox2").attr('disabled', true); $("#searchbox3").attr('disabled', true); $("#enter").hide(); $("#loading").show(); $("#placeholder").empty(); console.log(ui.item['label']); window.bOne = [ui.item['label'], "left"];  window.side = "left"; getKWflotData(); /*location.href=getURLbuild[ui.item['label']];*/ }
		});
		$( "#searchbox3" ).autocomplete({
			source: availableTags,
			select: function(event, ui) { window.mainFlotTimeseries = {}; $("#searchbox2").attr('disabled', true); $("#searchbox3").attr('disabled', true); $("#enter2").hide(); $("#loading2").show(); $("#placeholder2").empty(); console.log(ui.item['label']); window.bTwo = [ui.item['label'], "right"]; window.side = "right"; getKWflotData(); /*location.href=getURLbuild[ui.item['label']];*/ }
		});

	});



function pastDialog1(callback){
	$( "#pastdialog1" ).dialog({dialogClass: 'transparent',});
	$('#pastdialog1').dialog({ dialogClass:'transparent',   width:350, height:300/* insert your options */ , buttons: {"Background On/Off": function() { switchBG(); } }}).dialog('widget').position({ my: 'left top', at: 'left top', of: $("#dialogGoesHere") });
	callback();
}
function runGraph(){
	$.plot($("#flotholder2"), [[[1,1], [2, 2], [3, 3]]], {
			colors: ["blue", "black"],
        	legend: { noColumns: 2 },
        	xaxis: { tickDecimals: 0 },
        	selection: { mode: "x" },
			grid: {hoverable: true, clickable: true},
			xaxes: [{
				axisLabel: 'Time',
			}],
			yaxes: [{
				position: 'left',
				axisLabel: 'Power Consumption (kW)',
			}],
			series: {shadowSize: 0},
    	});
	$('.transparent').css('background-color','transparent');
	$('.transparent').css('overflow', 'hidden');
}

function switchBG(){
	//switches background of transparent dialog
	if($('.transparent').css('background-color')=='rgba(0, 0, 0, 0)'){
		$('.transparent').css('background-color','white');
	}
	else{
		$('.transparent').css('background-color','transparent');
	}
}

$(document).ready(function() {
	//time setup
	$("#loading").hide();
	$("#loading2").hide();
	window.bOne = "";
	window.bTwo = "";
	window.side = "";
	window.datefmt = "%W %M %e, %Y %H:%i"; //the format used by AnyTime, shared everywhere
	window.converter = new AnyTime.Converter( { format: window.datefmt }); //create a converter
	//create two time periods to set defaults
	nowDate = new Date();
	startDate = new Date(); 
	startDate.setTime(nowDate - 86400000);
	//Set values of user time-fields
	$("#date").val(converter.format(nowDate)); 
	$("#date2").val(converter.format(startDate));
	//Create pickers for each time-field
	AnyTime.picker( "date", { format: datefmt, firstDOW: 0 } );
	AnyTime.picker( "date2", { format: datefmt, firstDOW: 0 } );
	//end time setup


	//Initialize gauges

	//setup global variable replacements for passing along kW Timeseries data
	window.mainFlotTimeseries = {} //A dictionary for the data for the flot chart
	window.retrievedStatistics = {} //A dictionary to hold computed/retrieved data
console.log("{{ BUILD1 }}");
console.log("{{ BUILD2 }}");

if(("{{ BUILD1 }}" != "") && ("{{ BUILD2 }}" != "")){
	$( "#searchbox2" ).val("{{ BUILD1 }}");
	$( "#searchbox3" ).val("{{ BUILD2 }}");
	window.mainFlotTimeseries = {}; 
$("#enter").hide(); 
$("#loading").show(); 
$("#placeholder").empty(); 
//console.log(""); 
console.log("{{ buildings }}");
window.bOne = ["{{ BUILD1 }}", "left"];  
window.side = "left"; 
getKWflotData();
	setTimeout("initializer()", 3000);
}
});

function initializer(){
window.mainFlotTimeseries = {}; $("#enter2").hide(); $("#loading2").show(); $("#placeholder2").empty();  window.bTwo = ["{{ BUILD2 }}", "right"]; window.side = "right"; getKWflotData(); 
}

$("#refresh").click(function() {
	$("#placeholder").empty();
	$("#placeholder2").empty();
	$("#loading").show();
	$("#loading2").show();
	window.side = "left";
	getKWflotData();
	setTimeout("refRight()", 3000);
	});

function refRight(){
	window.side = "right";
	getKWflotData();
}

/*
 * 15 minute AutoUpdater
 * Refreshes (User-Time) based data 
 * 15 min interval is based on 15 min interval of sMAP apply nansum
 */
function autoUpdater(){
	if ($('input[name=autoup]').is(':checked')){
	var nowDate = new Date();
	$("#date").val(window.converter.format(nowDate));
	getKWflotData();
	window.side = "left";
	getKWflotData();
	setTimeout("refRight()", 3000);
	}
}


/*
 * Starts chain to fetch data for main flot chart
 */
function getKWflotData() {
	console.log(window.side);
	if (window.side=="left"){
		selection = window.bOne;
	}
	else{
		selection = window.bTwo;
	}
	getBaselineTags(function(resp){
		output = [];
		//sendUUIDcount = document.getElementById('UUIDcount');
		//sendUUIDcount.innerHTML = resp.length;
		if (resp.length==0){ //continues the fetch chain for buildings without a baseline
			noBaselineHandler();  //buildings getting data the new way launch into noBaselineHandler()
		}
		else{ //continues the fetch chain for buildings with a baseline
					output.push([resp[0]["uuid"],resp[0]["Metadata"]["Extra"]["Operator"]]); //REMOVE THIS
					window.mainFlotTimeseries[resp[0]["Metadata"]["Extra"]["Operator"]] = resp[0]["uuid"]; //for autoupdater use, at somepoint, rewrite the rest to make this replace output
			runHttpGetData(output);
		}
	}, selection[0]);
}



function noBaselineHandler(){
	var endtime = window.converter.parse($("#date").val()).getTime();
	var starttime = window.converter.parse($("#date2").val()).getTime();
	if (window.side=="left"){
		selection = window.bOne;
	}
	else{
		selection = window.bTwo;
	}
	getBuildingNansum(function(resp){
		passalong = [resp, [{"uuid": "BLANK", "Readings": []}]];
		window.mainFlotTimeseries['actualkW'] = resp[0]['Readings']
		var needToavg = [];
	
		if (endtime-starttime<=1209600000){
			for (x in passalong[0][0]['Readings']){
				needToavg.push(passalong[0][0]['Readings'][x][1]);
			}
			var psArray = new ps.array(needToavg);
			var avg = psArray.mean();
			var avgArr = [[starttime, avg], [endtime, avg]];
		}
		else {
				var avgArr = 0; 
		}

		types = ["subsampled sum", "baseline-01"];
		drawGraph(avgArr);

	}, selection[0], starttime, endtime);
}




function baselineHandler(latest, numMod, typeOrder){
	var converter = new AnyTime.Converter( { format: datefmt });
	var endtime = converter.parse($("#date").val()).getTime();
	var starttime = converter.parse($("#date2").val()).getTime();
	if (window.side=="left"){
		selection = window.bOne;
	}
	else{
		selection = window.bTwo;
	}
	httpGetTagsWINP(function(resp, inp, inptype, numMod){
		inp[numMod] = resp;

		if (endtime-starttime<=1209600000){
			for (x in inp[numMod][0]['Readings']){
				needToavg.push(inp[numMod][0]['Readings'][x][1]);
			}
			var psArray = new ps.array(needToavg);
			var avg = psArray.mean();
			var avgArr = [[starttime, avg], [endtime, avg]];
			}
			else {var avgArr = 0; }

		window.mainFlotTimeseries['actualkW'] = resp[0]['Readings'];
		drawGraph(avgArr);
}, "apply nansum(axis=1) < paste < window(first, field='minute', increment=1) < units to  data in (" + starttime + ", " + endtime + ") streamlimit 10000 where (Metadata/Extra/System = 'electric' or Metadata/Extra/System = 'total')  and ((Properties/UnitofMeasure = 'kW' or Properties/UnitofMeasure = 'Watts') or Properties/UnitofMeasure = 'W') and Metadata/Location/Building like '" + selection[0] + "%' and not Metadata/Extra/Operator like 'sum%' and not Path like '%demand'", latest, typeOrder, numMod);
}


function runHttpGetData(output) {
	latest = [];
	typeOrder = [];
	needToavg = [];
	var converter = new AnyTime.Converter( { format: datefmt });
	var endtime = converter.parse($("#date").val()).getTime();
	var starttime = converter.parse($("#date2").val()).getTime();

	for(x=0; x<output.length; x++){
	httpGetData(function(resp, typeInput){
		typeOrder.push(typeInput);
		latest.push(eval(resp));
		window.mainFlotTimeseries['baselineData'] = eval(resp)[0]['Readings'];
		if (output.length==latest.length){
			if (endtime-starttime<=1209600000){
			for (x in latest[0][0]['Readings']){
				needToavg.push(latest[0][0]['Readings'][x][1]);
			}
			var psArray = new ps.array(needToavg);
			var avg = psArray.mean();
			var avgArr = [[starttime, avg], [endtime, avg]];
			}
			else {var avgArr = 0; }
///FIX it up code here
			if(typeOrder[0]=="subsampled sum" && latest[0][0]['Readings'].length == 0 ){
				baselineHandler(latest, 0, typeOrder);
				return;
			}
			else if((typeOrder[0] == "baseline-01" && typeOrder.length==1) || (typeOrder[1]=="subsampled sum" && latest[1][0]['Readings'].length == 0)){
				
				if(typeOrder.length==1){
					typeOrder[1] = "subsampled sum";
				}
				baselineHandler(latest, 1, typeOrder);
				return;
			}



///END Fix it up code
			latest = drawGraph(avgArr);
			//setAllTheGauges(latest[0][0]['Readings'][latest[0][0]['Readings'].length-1], latest[1][0]['Readings'][latest[1][0]['Readings'].length-1]);
			runStats(latest, typeOrder, avgArr);

		}
	}, latest, output[x][0], starttime, endtime, output, output[x][1]);
	}
}


/*
 * Draws the main (top-centered) flot chart on each page
 * Runs after all necessary data is collected
 */
function drawGraph(flatlineAvg){
	var buildupData = [];
	var labels = [];
	if(typeof mainFlotTimeseries['actualkW']=='object'){
		buildupData.push({label:"Actual Usage", "data":mainFlotTimeseries['actualkW']});
	}
	if(typeof mainFlotTimeseries['baselineData']=='object'){
		buildupData.push({label:"Predicted Usage", "data":mainFlotTimeseries['baselineData']});
	}

	//Now fix timezone offset for flot
	
	////Figure out what to do here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	needTzOffset = new Date();
	tzOffset = needTzOffset.getTimezoneOffset()*60000
	/*
	for (x=0; x<inputData.length; x++){
		for (y=0; y<inputData[x][0]['Readings'].length; y++){
			inputData[x][0]['Readings'][y][0] = inputData[x][0]['Readings'][y][0]-tzOffset;
		}
	}
	if (flatlineAvg != 0){
	flatlineAvg[0][0] -= tzOffset;
	flatlineAvg[1][0] -= tzOffset;
	}
	*/
	//end fix timezone offset for flot
	var options = {
			colors: ["blue", "black"],
        	legend: { noColumns: 2 },
        	xaxis: { tickDecimals: 0, mode:"time" },
        	selection: { mode: "x" },
			grid: {hoverable: true, clickable: true},
			xaxes: [{
				axisLabel: 'Time',
			}],
			yaxes: [{
				position: 'left',
				axisLabel: 'Power Consumption (kW)',
			}],
			series: {shadowSize: 0},
    	};
	if (window.side=="left"){
		selection = window.bOne;
		var placeholder = $("#placeholder");
	}
	else{
		selection = window.bTwo;
		var placeholder = $("#placeholder2");
	}
//	var placeholder = $("#placeholder");

	placeholder.bind("plotselected", function (event, ranges) {
		$("#selection").text(ranges.xaxis.from.toFixed(1) + " to " + ranges.xaxis.to.toFixed(1));
		plot = $.plot(placeholder, buildupData, $.extend(true, {}, options, { xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to } }));
	});

	placeholder.bind("plotunselected", function (event) {
		$("#selection").text("");
	});

	var previousPoint = null;
    placeholder.bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));

        if (true) {
            if (item) {
                if (previousPoint != item.dataIndex) {
                    previousPoint = item.dataIndex;
                    
                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(2),
                        y = item.datapoint[1].toFixed(2);
                    
					var tempdate = new Date(x/1+tzOffset);
                    showTooltip(item.pageX, item.pageY,
                                item.series.label + " on " + converter.format(tempdate)  + " was " + y + " kW");
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;            
            }
        }
    });

    placeholder.bind("plotclick", function (event, pos, item) {
        if (item) {
            $("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");
            plot.highlight(item.series, item.datapoint);
        }
    });
	if (window.side=="left"){
		//selection = window.bOne;
		//var placeholder = $("#placeholder");
		$("#loading").hide()
		
	}
	else{
		//selection = window.bTwo;
		//var placeholder = $("#placeholder2");
		$("#loading2").hide()
		
	}

	var plot = $.plot(placeholder, buildupData, options);
	$("#searchbox2").attr('disabled', false); $("#searchbox3").attr('disabled', false);
}

/*
 * Helper for showing tooltips on flot chart
 */
function showTooltip(x, y, contents) {
		if (x<800){
			x = x;
		} else if (x<1100){
			x = x-300;
		} else{
			x = x-560;
		}
        $('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y + 5,
            left: x + 5,
            border: '1px solid #fdd',
            padding: '5px',
            'background-color': '#000',
			'color': '#FFF',
            opacity: 0.70,
			'font-size': '140%',
        }).appendTo("body").fadeIn(200);
}
</script>
{% endblock %}
